import JSEncrypt from 'jsencrypt';

// 公钥
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvOL18in6KF0DlXLZsGXg
m1fp3Ked/Qf6H8ZNy6yzPiXWkAmg9WgE36zUMgRikyEqu6lGw0AyQSPl8YzyHUh/
6VlJE11mpkISvEoFtkwbsTKl+vGmkMiJL/8za/J+Ddy1EJihr0F/gp8TDaOjODBN
64P2NSdnGFgSFvsPXPYJyACnxZYe/ZQ9zs1HlG/+VbI7/LJUap8yvG6qgMYTvVpl
QhmnVNG6xu1G4200vWZ2PRhmQocR8lvDPvVaGdNLW1IXVBRY4+coJANOrl95bRjj
9t5dbhHAcZsZqKqkHdZJ47zx6GjMry/DFPpzlZliu1uIrvtZo9RwKbY0qv9onRYr
CwIDAQAB
-----END PUBLIC KEY-----`;

const PRIVATE_KEY = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC84vXyKfooXQOV
ctmwZeCbV+ncp539B/ofxk3LrLM+JdaQCaD1aATfrNQyBGKTISq7qUbDQDJBI+Xx
jPIdSH/pWUkTXWamQhK8SgW2TBuxMqX68aaQyIkv/zNr8n4N3LUQmKGvQX+CnxMN
o6M4ME3rg/Y1J2cYWBIW+w9c9gnIAKfFlh79lD3OzUeUb/5Vsjv8slRqnzK8bqqA
xhO9WmVCGadU0brG7UbjbTS9ZnY9GGZChxHyW8M+9VoZ00tbUhdUFFjj5ygkA06u
X3ltGOP23l1uEcBxmxmoqqQd1knjvPHoaMyvL8MU+nOVmWK7W4iu+1mj1HAptjSq
/2idFisLAgMBAAECggEACo6WCw789Z5eC2j/MSRyI8YlNeYQAF4eq2grEL9AlP1X
Z/bpzjceNdD6jfSzYu0sVSj2YZ/oAlg6/ox11PYoem0F/Q7JpHEDJai7d5j6xgu1
ipHqaqNfeFVhCEXMdTWvNwclp95wyoB3Xg1JAf4N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KaOVvmFlJjaQhca7tTi377hH
-----END PRIVATE KEY-----`

/**
 * 使用 RSA 公钥加密字符串
 * @param text 要加密的明文
 * @param publicKey 可选，自定义公钥
 * @returns Base64 编码的密文，失败返回 false
 */
export function rsaEncrypt(text: string, publicKey: string = PUBLIC_KEY): string | null{
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey);
    const result= encryptor.encrypt(text);
    return result === false ? null : result;
}

/**
 * （可选）RSA 解密（一般前端不用）
 * @param encryptedText Base64 编码的密文
 * @param privateKey 私钥
 * @returns 明文，失败返回 false
 */
export function rsaDecrypt(encryptedText: string, privateKey: string = PRIVATE_KEY): string | null {
    const encryptor = new JSEncrypt();
    encryptor.setPrivateKey(privateKey);
    const result= encryptor.decrypt(encryptedText);
    return result === false ? null : result;
}